package org.meb.lotrlcg.web.ctrl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.meb.lotrlcg.db.model.Domain;
import org.meb.lotrlcg.web.services.SearchService;
import org.meb.lotrlcg.web.services.User;

@ApplicationScoped
public class DictCache<T> implements Serializable {

	private static final long serialVersionUID = -6370789979840058937L;
	
	private Map<String, List<T>> itemsMap;
	private ReadWriteLock lock = new ReentrantReadWriteLock();

	@Inject
	private User user;
	
	@Inject
	private SearchService searchService;

	public List<T> items() {
		List<T> items = null;

		Lock readLock = lock.readLock();
		Lock writeLock = lock.writeLock();
		try {
			String language = user.getLanguage();

			readLock.lock();
			if (itemsMap.containsKey(language)) {
				items = itemsMap.get(language);
			} else {
				writeLock.lock();
				if (itemsMap.containsKey(language)) {
					items = itemsMap.get(language);
				} else {
					searchService.find(new Domain());
				}
			}
		} finally {
			writeLock.unlock();
			readLock.unlock();
		}

		return items;
	}
}
